package org.dromara.comm_lhz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.dromara.comm_lhz.entity.AsSpaceImgEntity;
import org.dromara.comm_lhz.entity.AsSpaceManageEntity;
import org.dromara.comm_lhz.entity.dto.AsSpaceDto;
import org.dromara.comm_lhz.mapper.AsSpaceManageHMapper;
import org.dromara.comm_lhz.service.AsSpaceImgHService;
import org.dromara.comm_lhz.service.AsSpaceManageHService;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 空间管理表(AsSpaceManage)表服务实现类
 */

@Service
public class AsSpaceManageHHServiceImpl extends ServiceImpl<AsSpaceManageHMapper, AsSpaceManageEntity> implements AsSpaceManageHService {

    @Autowired
    private AsSpaceManageHMapper asSpaceManageHMapper;

    @Autowired
    private AsSpaceImgHService asSpaceImgHService;


    /**
     * 查询空间详情
     *
     * @param asSpaceManageEntity 包含要查询的空间ID的实体
     * @return 空间详情，以 AsSpaceDto 形式返回
     */
    @Override
    public AsSpaceDto selSpaceManage(AsSpaceManageEntity asSpaceManageEntity) {
        // 根据ID查询空间管理实体
        AsSpaceManageEntity spaceManageEntity = asSpaceManageHMapper.selectById(asSpaceManageEntity.getId());

        // 将实体转换为 DTO
        AsSpaceDto asSpaceDto = BeanUtil.copyProperties(spaceManageEntity, AsSpaceDto.class);

        // 查询与该空间相关的图片路径，并设置到 DTO 中
        List<String> imagePaths = asSpaceImgHService.lambdaQuery()
            .eq(AsSpaceImgEntity::getSpaceId, asSpaceDto.getId())
            .list()
            .stream()
            .map(AsSpaceImgEntity::getUrl)
            .toList();
        asSpaceDto.setImagePaths(imagePaths);

        // 返回空间详情 DTO
        return asSpaceDto;
    }

    /**
     * 单条添加数据
     *
     * @param asSpaceDto 空间DTO对象，包含空间的基本信息和图片路径列表
     */
    @Override
    public void insert(AsSpaceDto asSpaceDto) {
        // 空间基本信息
        AsSpaceManageEntity asSpaceManageEntity = BeanUtil.copyProperties(asSpaceDto, AsSpaceManageEntity.class);
        // 保存空间基本信息
        this.save(asSpaceManageEntity);
        // 更新DTO中的空间ID，以便后续操作
        asSpaceDto.setId(asSpaceManageEntity.getId());

        // 提取图片路径列表，并转换为图片实体列表
        List<String> imagePaths = asSpaceDto.getImagePaths();
        List<AsSpaceImgEntity> asSpaceImgEntities = imagePaths.stream().map(imagePath -> {
            AsSpaceImgEntity asSpaceImgEntity = new AsSpaceImgEntity();
            // 设置图片所属空间的ID
            asSpaceImgEntity.setSpaceId(asSpaceDto.getId());
            // 设置图片路径
            asSpaceImgEntity.setUrl(imagePath);
            return asSpaceImgEntity;
        }).toList();

        // 批量保存空间图片信息
        asSpaceImgHService.saveBatch(asSpaceImgEntities);
    }

    @Override
    public void update(AsSpaceDto asSpaceDto) {
        // 将 DTO 转换为实体
        AsSpaceManageEntity asSpaceManageEntity = BeanUtil.copyProperties(asSpaceDto, AsSpaceManageEntity.class);
        // 更新空间基本信息
        asSpaceManageHMapper.updateById(asSpaceManageEntity);
        // 获取当前空间的图片路径列表
        List<String> imagePaths = asSpaceDto.getImagePaths();
        // 删除该空间的旧图片信息
        asSpaceImgHService.remove(new QueryWrapper<AsSpaceImgEntity>().lambda()
            .eq(AsSpaceImgEntity::getSpaceId, asSpaceManageEntity.getId()));

        // 将新的图片路径转换为图片实体列表
        List<AsSpaceImgEntity> asSpaceImgEntities = imagePaths.stream().map(imagePath -> {
            AsSpaceImgEntity asSpaceImgEntity = new AsSpaceImgEntity();
            // 设置图片所属空间的ID
            asSpaceImgEntity.setSpaceId(asSpaceManageEntity.getId());
            // 设置图片路径
            asSpaceImgEntity.setUrl(imagePath);
            return asSpaceImgEntity;
        }).toList();

        // 批量保存新的空间图片信息
        asSpaceImgHService.saveBatch(asSpaceImgEntities);
    }

    /**
     * 分页查询空间列表
     *
     * @param pageable 分页信息（页码和大小）
     * @return 分页后的空间列表，包含空间详情的对象
     */
    @Override
    public Page<AsSpaceDto> getSpaceManage(Pageable pageable, String detailsName) {
        // 创建 MyBatis-Plus 分页对象
        Page<AsSpaceManageEntity> page = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());

        // 创建查询条件的 QueryWrapper
        QueryWrapper<AsSpaceManageEntity> queryWrapper = new QueryWrapper<>();

        // 如果提供了搜索关键字，则添加模糊查询条件
        if (detailsName != null && !detailsName.isEmpty()) {
            queryWrapper.lambda().like(AsSpaceManageEntity::getDetailsName, detailsName);
        }

        // 查询分页后的空间管理实体列表
        Page<AsSpaceManageEntity> spaceManagePage = asSpaceManageHMapper.selectPage(page, queryWrapper);

        // 将实体列表转换为 DTO 列表
        List<AsSpaceDto> asSpaceDtos = spaceManagePage.getRecords().stream()
            .map(entity -> {
                AsSpaceDto dto = BeanUtil.copyProperties(entity, AsSpaceDto.class);

                // 查询并设置每个空间的图片路径
                List<String> imagePaths = asSpaceImgHService.lambdaQuery()
                    .eq(AsSpaceImgEntity::getSpaceId, dto.getId())
                    .list()
                    .stream()
                    .map(AsSpaceImgEntity::getUrl)
                    .toList();
                dto.setImagePaths(imagePaths);

                return dto;
            })
            .collect(Collectors.toList());

        // 将转换后的 DTO 列表封装到 MyBatis-Plus 的 Page 对象中
        Page<AsSpaceDto> resultPage = new Page<>(spaceManagePage.getCurrent(), spaceManagePage.getSize(), spaceManagePage.getTotal());
        resultPage.setRecords(asSpaceDtos);

        return resultPage;
    }


    @Override
    public AsSpaceManageEntity selectAsSponsorAll(AsSpaceManageEntity asSpaceManageEntity) {
        return asSpaceManageHMapper.selectById(asSpaceManageEntity.getId());
    }

    @Override
    public List<Object> selectAsSpaceManageEntity(AsSpaceManageEntity asSpaceManageEntity) {
        List<Object> list = new ArrayList<>();

        // 创建一个查询条件构造器
        LambdaQueryWrapper<AsSpaceManageEntity> wrapper = new LambdaQueryWrapper<>();
        // 根据当前用户ID进行过滤
        wrapper.eq(AsSpaceManageEntity::getUserId, LoginHelper.getUserId());

        // 检查传入的状态是否为0，如果是，则按状态过滤
        if (asSpaceManageEntity.getState() != null) {
            wrapper.eq(AsSpaceManageEntity::getState, asSpaceManageEntity.getState());
        }

        // 执行查询
        List<AsSpaceManageEntity> asSpaceManageEntities = asSpaceManageHMapper.selectList(wrapper);

        // 将结果添加到列表中
        list.add(asSpaceManageEntities);

        return list;
    }

}
